﻿using AutoMapper;
using MediatR;
using SmartTracking.API.Write.Application.Commands.Role_command;
using SmartTracking.Domain.UserInfo;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace SmartTracking.API.Write.Application.CommandHandlers.Role_handler
{
    public class AddRoleCommandHandler:IRequestHandler<AddRoleCommand,ApiResult<int>>
    {
        private readonly IBaseRepository<Roles> roleRep;
        private readonly IBaseRepository<RolePermissionsMiddle> rolePermissionRep;
        private readonly IMapper mapper;

        public AddRoleCommandHandler(
            IBaseRepository<Roles> roleRep,
            IBaseRepository<RolePermissionsMiddle> rolePermissionRep,
            IMapper mapper)
        {
            this.roleRep = roleRep;
            this.rolePermissionRep = rolePermissionRep;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(AddRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            result.Code = ApiEnum.新增成功;
            result.Message = ApiEnum.新增成功.ToString();

            using (var tran = roleRep.DB.Database.BeginTransaction())
            {
                try
                {
                    #region 添加角色
                    Roles roles = mapper.Map<Roles>(request);
                    roles.CreateTime = DateTime.Now;
                    roles.IsDeleted = false;
                    int list = await roleRep.AddAsync(roles);
                    #endregion

                    #region 添加角色权限
                    List<RolePermissionsMiddle> rolePermission = new List<RolePermissionsMiddle>();
                    foreach (var item in request.PermissionId)
                    {
                        rolePermission.Add(new RolePermissionsMiddle
                        {
                            RoleId = roles.RoleId,
                            PermissionId = item
                        });
                    }
                    await rolePermissionRep.AddRangeAsync(rolePermission);
                    #endregion
                    // 提交事务
                    tran.Commit();
                    result.data = list;
                }
                catch (Exception ex)
                {
                    result.Code = ApiEnum.新增失败;
                    result.Message = ApiEnum.新增失败.ToString() +","+ ex.Message;
                    //回滚事务
                    tran.Rollback();
                }
            }
            return result;
        }
    }
}
